package com.hmdp.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import static com.hmdp.utils.RegexUtils.isPhoneInvalid;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if (isPhoneInvalid(phone)){
            //2.检验不符合返回错误信息
            return Result.fail("手机号格式错误");
        }
        //3.检验成功生成验证码
        String code= RandomUtil.randomString(6);
        //4.保存验证码到session
        session.setAttribute("code",code);

        //5.发送验证码返回ok
        log.debug("发送验证码成功，验证码为{}",code);


        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.验证手机号
        String phone=loginForm.getPhone();
        if (isPhoneInvalid(phone)){
            //2.检验不符合返回错误信息
            return Result.fail("手机号格式错误");
        }
        //2.校验验证码
        Object cacheCode=session.getAttribute("code");
        String code=loginForm.getCode();
        if (cacheCode==null||!cacheCode.toString().equals(code)) {
            //3.不一致返回错误信息
            return Result.fail("验证码错误");
        }
        //4.一致根据手机号查询用户
        User user = query().eq("phone", phone).one();
        //5.不存在创建用户
        if (user==null)
            user=creatUserByPhone(phone);
        //6.一致保存数据
        session.setAttribute("user",user);
        //7.返回ok
        return Result.ok();
    }

    private User creatUserByPhone(String phone) {
        User user=new User();
        user.setPhone(phone);
        user.setNickName("DP"+RandomUtil.randomString(8));
        return user;
    }
}
